'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { IconArrowLeft, IconTrash } from '@tabler/icons-react';

interface FoodItem {
  name: string;
  amount: string;
  calories: number;
  protein: number;
  carbs: number;
  fat: number;
}

interface DietRecordFormProps {
  initialData?: {
    id?: string;
    date: string;
    mealType: string;
    foods: FoodItem[];
  };
  mode: 'add' | 'edit';
}

export default function DietRecordForm({ initialData, mode }: DietRecordFormProps) {
  const router = useRouter();
  const [date, setDate] = useState(initialData?.date || new Date().toISOString().split('T')[0]);
  const [mealType, setMealType] = useState(initialData?.mealType || 'breakfast');
  const [foods, setFoods] = useState<FoodItem[]>(
    initialData?.foods || [{ name: '', amount: '', calories: 0, protein: 0, carbs: 0, fat: 0 }]
  );

  const addFoodItem = () => {
    setFoods([...foods, { name: '', amount: '', calories: 0, protein: 0, carbs: 0, fat: 0 }]);
  };

  const removeFoodItem = (index: number) => {
    setFoods(foods.filter((_, i) => i !== index));
  };

  const updateFoodItem = (index: number, field: keyof FoodItem, value: string | number) => {
    const newFoods = [...foods];
    newFoods[index] = { ...newFoods[index], [field]: value };
    setFoods(newFoods);
  };

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
      const url = mode === 'add' ? '/api/diet/records' : `/api/diet/record/${initialData?.id}`;
      const method = mode === 'add' ? 'POST' : 'PUT';
      
      const response = await fetch(url, {
        method,
        headers: { 'Content-Type': 'application/json' },
        credentials: 'include',
        body: JSON.stringify({
          date,
          mealType,
          foods,
        }),
      });

      if (!response.ok) throw new Error('提交失败');
      
      router.push('/diet-record');
      router.refresh();
    } catch (error) {
      console.error('提交饮食记录失败:', error);
      alert('提交失败，请稍后重试');
    }
  };

  return (
    <div className="max-w-4xl mx-auto">
      <div className="bg-white rounded-lg shadow-sm">
        <div className="p-6">
          <div className="flex items-center gap-4 mb-6">
            <button
              onClick={() => router.back()}
              className="text-gray-600 hover:text-gray-900"
            >
              <IconArrowLeft className="w-5 h-5" />
            </button>
            <h1 className="text-2xl font-bold">
              {mode === 'add' ? '添加饮食记录' : '编辑饮食记录'}
            </h1>
          </div>

          <form onSubmit={handleSubmit}>
            <div className="grid grid-cols-2 gap-4 mb-6">
              <div>
                <label className="block text-sm font-medium mb-1">日期</label>
                <input
                  type="date"
                  value={date}
                  onChange={(e) => setDate(e.target.value)}
                  className="input-field w-full"
                  required
                />
              </div>
              <div>
                <label className="block text-sm font-medium mb-1">餐次</label>
                <select
                  value={mealType}
                  onChange={(e) => setMealType(e.target.value)}
                  className="input-field w-full"
                  required
                >
                  <option value="breakfast">早餐</option>
                  <option value="lunch">午餐</option>
                  <option value="dinner">晚餐</option>
                  <option value="snack">零食</option>
                </select>
              </div>
            </div>

            <div className="space-y-4">
              {foods.map((food, index) => (
                <div key={index} className="grid grid-cols-6 gap-4 items-start">
                  <div className="col-span-2">
                    <input
                      type="text"
                      placeholder="食物名称"
                      value={food.name}
                      onChange={(e) => updateFoodItem(index, 'name', e.target.value)}
                      className="input-field w-full"
                      required
                    />
                  </div>
                  <div>
                    <input
                      type="text"
                      placeholder="数量"
                      value={food.amount}
                      onChange={(e) => updateFoodItem(index, 'amount', e.target.value)}
                      className="input-field w-full"
                      required
                    />
                  </div>
                  <div>
                    <input
                      type="number"
                      placeholder="热量(kcal)"
                      value={food.calories || ''}
                      onChange={(e) => updateFoodItem(index, 'calories', Number(e.target.value))}
                      className="input-field w-full"
                      required
                    />
                  </div>
                  <div>
                    <input
                      type="number"
                      placeholder="蛋白质(g)"
                      value={food.protein || ''}
                      onChange={(e) => updateFoodItem(index, 'protein', Number(e.target.value))}
                      className="input-field w-full"
                      required
                    />
                  </div>
                  <div className="flex items-center gap-2">
                    <input
                      type="number"
                      placeholder="碳水(g)"
                      value={food.carbs || ''}
                      onChange={(e) => updateFoodItem(index, 'carbs', Number(e.target.value))}
                      className="input-field w-full"
                      required
                    />
                    {foods.length > 1 && (
                      <button
                        type="button"
                        onClick={() => removeFoodItem(index)}
                        className="text-red-500 hover:text-red-700 p-2 rounded-full hover:bg-red-50"
                        title="删除"
                      >
                        <IconTrash className="w-5 h-5" />
                      </button>
                    )}
                  </div>
                </div>
              ))}
            </div>

            <div className="mt-4 flex justify-between">
              <button
                type="button"
                onClick={addFoodItem}
                className="text-blue-600 hover:text-blue-700 font-medium"
              >
                + 添加食物
              </button>
              <button type="submit" className="btn-primary">
                {mode === 'add' ? '添加记录' : '保存修改'}
              </button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
} 